<?php

/**
 * 商品分类控制器
 */
class CategoryAction extends CommonAction {

    /**
     * 商品分类显示
     * @return [type]
     */
    public function index() {
        import('ORG.Util.Page');
        $db = M('category');
        $page = new Page($db->count('cid'), 10);
        $result = $db->select();
        $result = category_recursion($result, 0, 2); //重组分类
        $result = array_slice($result, $page->firstRow, $page->listRows); //分页实现
        $this->data = $result;
        $this->page = $page->show();
        $this->display();
    }

    /**
     * 增加栏目视图
     */
    public function addShow() {
        $pid = isset($_GET['cid']) ? (int) $_GET['cid'] : 0;
        $db = M('category');
        $result = $db->where(array('cid' => $pid))->field('name')->find();
        $this->data = $result;
        $type = M('type')->select();
        $this->type = $type;
        $this->display();
    }

    /**
     * 增加栏目实现
     */
    public function add() {
        $name = $this->_post('name');
        $data = array(
            'name' => $name,
            'pid' => (int) $_POST['pid'],
            'type_id' => (int) $_POST['type_id']
        );
        if (M('category')->data($data)->add()) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }

    /**
     * 编辑栏目视图
     * @return [type]
     */
    public function editshow() {
        $cid = (int) $_GET['cid'];
        $result = D('CategoryView')->where(array('cid' => $cid))->find();
        p($result);
        $type = M('type')->select();
        $this->type = $type;
        $this->data = $result;
        $this->display();
    }

    /**
     * 编辑栏目实现
     */
    public function edit() {
        $data = array(
            'cid' => (int) $_POST['cid'],
            'name' => $this->_post('name'),
            'type_id' => (int) $_POST['type_id']
        );
        if (M('category')->data($data)->save()) {
            $this->success('分类修改成功', U('Category/index'));
        } else {
            $this->error('分类修改失败');
        }
    }

    /**
     * 删除栏目
     * @return [type]
     */
    public function del() {
        $cid = (int) $_GET['cid'];
        if (M('category')->where(array('cid' => $cid))->delete()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

}

?>